import axios from 'axios'
import authHeader from '../services/auth-header';
import store from '../store'

export const Axios = axios.create({
  baseURL:  'http://127.0.0.1:8000',
  timeout: 10000,
})

//POST传参序列化(添加请求拦截器)
 // 在发送请求之前做某件事
Axios.interceptors.request.use(config => {
    let user = JSON.parse(localStorage.getItem('user'));
    if (localStorage.getItem('user')) {
        config.headers.Authorization = 'Bearer ' + user.access
    }
    store.state.isLoading = true

    return config
},error =>{
    alert("错误的传参", 'fail')
    return Promise.reject(error)
})


// response interceptor
// http response 响应拦截器
Axios.interceptors.response.use(response => {
        store.state.isLoading = false
    return response;
},error => {
    if (error.response) {
        switch (error.response.status) {
            // 返回401，清除token信息并跳转到登录页面
            case 401:
            localStorage.removeItem('user');
            router.replace({
                path: '/login'
                //登录成功后跳入浏览的当前页面
                // query: {redirect: router.currentRoute.fullPath}
            })
        }
            store.state.isLoading = false
        // 返回接口返回的错误信息
        return Promise.reject(error.response.data);
    }
});



export default {
  install: function (Vue) {
    Object.defineProperty(Vue.prototype, '$http', {value: axios})
  }
}
